<template>
    <div class="content">
        <TableLayout form-title="">
            <el-form :model="formInline" class="formInline" label-width="100px"  ref="formInline" slot="form" v-collapse="false" :rules="rules">          
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="所属省" prop="fProvinceId">
                            <province v-model="formInline.fProvinceId" @change="changeprvice"></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属市">
                            <city v-model="formInline.fCityId" :province="formInline.fProvinceId"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属区县">
                            <region v-model="formInline.fAreaId" :city="formInline.fCityId"></region>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学校名称">
                            <school v-model="formInline.schoolName" :provinceId="formInline.fProvinceId" :cityId="formInline.fCityId" :areaId="formInline.fAreaId" style="width:100%" @change='schoolChange'></school>
                        </el-form-item>
                    </el-col> 
                    <el-col :span="8">
                        <el-form-item label="负责人姓名">
                                <el-input v-model="formInline.leaderName" placeholder="请输入内容" :maxlength="6"></el-input>
                        </el-form-item>
                    </el-col> 
                    <el-col :span="8">
                        <el-form-item label="负责人电话" prop="loginNum">
                                <el-input v-model="formInline.loginNum" placeholder="请输入内容" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="是否培训机构">
                            <el-select v-model="formInline.typeStatus" style="width:100%" @change="emptySchoolType">
                                <el-option v-for="item in statusType" :key="item.orgId" :label="item.statusName" :value="item.orgId"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col> 
                    
                    <el-col :span="8">
                        <el-form-item label="学校类型" v-if="formInline.typeStatus=='0'">
                            <el-select v-model="formInline.typeSchool" placeholder="请选择" style="width:100%" >
                                <el-option v-for="item in formInline.dataType" :key="item.schoolTypeId" :label="item.typeName" :value="item.schoolTypeId"> </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>                     
                </el-row>
                <div class="top-line">
                    <el-button type="primary" @click="onSubmit('formInline')">查询</el-button>
                </div>
            </el-form>
 
            <div class="table-title" slot="table-title">               
                <div class="btnPosition">
                    <el-button  @click="goToAddRole">添加学校</el-button>
                    <!-- 2017/12/14 by cuihd (产品要求删除的，但是没有写流转单) -->
                    <!-- <el-button  @click="batchOpenCms">开启短信</el-button> -->
                    <!-- <el-button  @click="batchCloseCms">关闭短信</el-button> -->
                    <el-button  @click="deleteRole">批量删除</el-button>
                </div>
            </div>
            <el-table :data="dataApply" style="width: 100%" border @selection-change="handleSelectionChange" v-loading="loading" ref="multipleTable">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
 
                <el-table-column label="学校名称" align="center"  prop="schoolName" width="170" >
                    <template scope="scope">
                        <span>{{scope.row.schoolName | isNull}}</span>
                    </template>
                </el-table-column>
                
                <el-table-column label="学校类型" align="center" prop="schoolType" width="100">
                    <template scope="scope">
                        <span>{{scope.row.schoolType | isNull}}</span>
                    </template>
                </el-table-column>
 
                <el-table-column label="所属地区" align="center" prop="belongToArea">
                    <template scope="scope">
                        <span>{{scope.row.belongToArea | isNull}}</span>
                    </template>
                </el-table-column>
                
                <el-table-column label="详细地址" align="center" prop="detail">
                    <template scope="scope">
                        <span>{{scope.row.detail | isNull}}</span>
                    </template>
                </el-table-column>
                
                <el-table-column label="创建时间" width="170" align="center" prop="createTime"> 
                    <template scope="scope">
                        <span>{{scope.row.createTime | filterCreateTime}}</span>
                    </template>
                </el-table-column>
                
                <el-table-column align="center" label="创建人" prop="creatorName" width="170">
                    <template scope="scope">
                        <span>{{scope.row.creatorName | isNull}}</span>
                    </template>
                </el-table-column>
                <!-- 2017/12/14 by cuihd (产品要求删除的，但是没有写流转单) -->
                <!-- <el-table-column label="短信状态" align="center" width="100">
                    <template scope="scope">
                        <span v-if="scope.row.messageStatus=='0'">关闭</span>
                        <span v-if="scope.row.messageStatus=='1'">开启</span>
                    </template>                 
                </el-table-column> -->
                
                <el-table-column label="负责人信息" align="center" width="110">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="goDetail(scope.row.schoolId)">详情</el-button>
                    </template>                 
                </el-table-column>
                
                <el-table-column align="center" label="科目" width="80">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="subjectDet(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
 
                <el-table-column align="left" label="其他操作" width="120">
                    <template scope="scope">
                        <!-- 2017/12/14 by cuihd (产品要求删除的，但是没有写流转单) -->
                        <!-- <el-button type="text" class="btn-success" @click="sigleStartCms(scope.row)" v-if="scope.row.messageStatus=='0'">开启短信</el-button> -->
                        <!-- <el-button type="text" class="btn-success" @click="sigleCloseCms(scope.row)" v-if="scope.row.messageStatus=='1'">关闭短信</el-button> -->
                        <el-button type="text" class="btn-success" @click="goToReviseRole(scope.row.schoolId)">修改</el-button>
                        <el-button type="text" class="btn-success" @click="deleteRow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>           
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="+listQuery.total"
                    :current-page.sync="listQuery.page"
                    :page-sizes="config.pageSizes"
                    :page-size="config.pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <subjectDetail :dialog="dialog" v-if="dialog.dialogFormVisible"></subjectDetail>
        <!-- created by cuihd at 20180711 优化批量删除学校 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>
 
<script>
import { querySchoolByPage, querySchoolType, batchDeleteSchool, startOrCloseMessage, batchDeleteSchoolProgress} from 'api/schoolManage';
import TableLayout from 'components/TableLayout';
import { mapState, mapActions, mapGetters } from 'vuex';
import subjectDetail from './subjectDetail';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import school from 'components/SchoolClasss/school';
import validate from '@/utils/validate';
 
export default{
    components: {TableLayout, subjectDetail, province, city, region, school},
    data() {
        return {
            fProvinceId: '',
            fCityId: '',
            fAreaId: '',
            query: '',
            restaurants: [],
            formInline: {// form表单数据
                leaderName: '',
                fProvinceId: '',
                fAreaId: '',
                fCityId: '',
                loginNum: '',
                schoolId: '',
                schoolName: '',
                typeStatus: '',
                typeSchool: '',
                schoolNameList: []
            },
            statusType: [
                {
                    orgId: '',
                    statusName: '请选择'
                },
                {
                    orgId: '0',
                    statusName: '否'
                },
                {
                    orgId: '1',
                    statusName: '是'
                }],
            dialog: {
                dialogFormVisible: false,
                pid: ''
            },
            checked: true,
            dataApply: [],
            dataNum: 1, // 表格1显示条数，初始为1
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            rules: {
                loginNum: [...validate.phone()],
                fProvinceId: [{required: true, message: '请选择省份' }]
            },
            loading: false,
            schoolLoading: false,
            multipleSelection: [],
            /**
             * created by cuihd at 20180709
             * 优化批量删除教师
             * 添加相关变量
             */
            dialogTitle: '正在批量删除学校...',
            dialogTimeout: false,
            progress: 0
        }
    },
   
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
        }),
        ...mapGetters([
            'uid'
        ])
    },
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val==2 && this.searchFetchData();
        }
    },
    // 初始化
    created() {
        // this.searchFetchData();
        this.getSchoolType();
    },
    filters: {
        filterCreateTime(val) {
            if (val) {
                return val.substr(0, val.length-2) 
            } else {
                return '--'
            }
        }
    },
    methods: {
        // 全局获取行数
        ...mapActions(['ChangePageSize']),
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        changeprvice() {
            // console.log('aaaaaaaaaa')
        },
        // 批量删除学校
        deleteRole() {
            if (this.multipleSelection.length<=0) {
                this.$message({
                    message: '请选择需要删除的学校'
                })
            }
            let roleIds = '';
            for (let i=0;i<this.multipleSelection.length;i++) {
                roleIds+=this.multipleSelection[i].schoolId+','; 
            }
            roleIds=roleIds.substring(0, roleIds.length-1)
            if (roleIds.length == 0) {
                return;
            }
            this.$confirm('此操作将批量删除选中学校, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.loading = true;
                batchDeleteSchool(roleIds).then(res => {
                    // this.searchFetchData();
                    // this.$message({
                    //     type: 'success',
                    //     message: '删除成功'
                    // })
                    /**
                     * created by cuihd at 20180710
                     * 优化批量删除教师
                     * 添加相关变量
                     */
                    this.loading = false;
                    let timeStamp = res.data.content.timeStamp;
                    let totalNum = res.data.content.totalNum;
                    this.dialogTitle = '正在批量删除学校...';
                    this.dialogTimeout = true;
                    this.progress = 0;
                    this.batchProgress(timeStamp, totalNum);
                }).catch(err => {
                    console.log(err);
                    this.loading = false;
                })
            }).catch(() => {
                this.loading = false;
                this.$message.info('已取消');
            });
        },
        // created by cuihd at 20180710
        // 轮询接口获取未处理的数量
        batchProgress(timeStamp, totalNum) { // 递归轮询接口
            totalNum = Number(totalNum); // 强转成number类型
            batchDeleteSchoolProgress(timeStamp).then(res => {
                if (res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null) {
                    if (res.data.content != 0) {
                        this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                        setTimeout(() => {
                            this.batchProgress(timeStamp, totalNum);
                        }, 1500);
                    } else {
                        this.btnLoading = false;
                        this.dialogTitle = '批量删除学校成功';
                        this.progress = 100;
                        setTimeout(() => {                       
                            this.dialogTimeout = false;
                            this.searchFetchData();
                        }, 500)
                    }
                } else {
                    this.dialogTimeout = false;
                    this.$message({
                        message: '批量删除失败！',
                        type: 'error'
                    });
                }
                
            }).catch(err => {
                console.log(err);
            })
        },
        // 批量开启短信
        batchOpenCms() {
            if (this.multipleSelection.length<=0) {
                this.$message({
                    message: '请选择要开启短信的学校'
                })
            }
            let roleIds = '';
            for (let i=0;i<this.multipleSelection.length;i++) {
                roleIds+=this.multipleSelection[i].schoolId+','; 
            }
            roleIds=roleIds.substring(0, roleIds.length-1)
            if (roleIds.length == 0) {
                return;
            }
            this.$confirm('此操作将批量开启短信提示, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                startOrCloseMessage(1, roleIds).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '开启成功'
                    })
                })
            }).catch(() => {
                this.$message.info('已取消');
            });
        },
        
        // 批量关闭短信
        batchCloseCms() {
            if (this.multipleSelection.length<=0) {
                this.$message({
                    message: '请选择要关闭的短信!'
                })
            }
            let roleIds = '';
            for (let i=0;i<this.multipleSelection.length;i++) {
                roleIds+=this.multipleSelection[i].schoolId+','; 
            }
            roleIds=roleIds.substring(0, roleIds.length-1)
            if (roleIds.length == 0) {
                return;
            }
            this.$confirm('此操作将批量关闭短信提示, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                startOrCloseMessage(0, roleIds).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '关闭成功'
                    })
                })
            }).catch(() => {
                this.$message.info('已取消');
            });
        },
        // 查询学校类型
        getSchoolType() {
            querySchoolType().then(response => {
                let schoolType = response.data.content;
                let select = {
                    typeName: '请选择',
                    schoolTypeId: ''
                }
                schoolType.unshift(select);
                this.formInline.dataType = schoolType;
            });
        },
        // 获取学校id
        schoolChange(val) {
            // console.log(val, this.formInline.schoolId)
            this.formInline.schoolId = val
        },
        // 单个删除学校
        deleteRow(rows) {
            let roleIds = rows.schoolId;
            this.$confirm('确定要删除此学校, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                batchDeleteSchool(roleIds).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    })
                })
            }).catch(() => {
                this.$message.info('已取消');
            });
        },
        // 单个开启短信
        sigleStartCms(rows) {
            let roleIds = rows.schoolId;
            this.$confirm('确定要开启短信?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                startOrCloseMessage('1', roleIds).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '开启成功'
                    })
                }) 
            }).catch(() => {
                this.$message.info('已取消');
            });
        },
        // 单个关闭短信
        sigleCloseCms(rows) {
            let roleIds = rows.schoolId;
            this.$confirm('确定要关闭短信?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                startOrCloseMessage('0', roleIds).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '关闭成功'
                    })
                }) 
            }).catch(() => {
                this.$message.info('已取消');
            });
        },
        handleSizeChange(val) {
            this.ChangePageSize(val);
            this.$refs.formInline.validate((valid) => {
                if (valid) {
                    this.listQuery.page = 1;
                    this.searchFetchData();
                }
            })
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        },
        // 查询列表
        searchFetchData() {
            if (!this.formInline.fProvinceId) {
                return;
            }
            this.loading = true;
            querySchoolByPage(this.listQuery.page, this.config.pageSize, this.formInline.fProvinceId, this.formInline.fCityId, this.formInline.fAreaId, this.formInline.schoolId, this.formInline.typeStatus, this.formInline.typeSchool, this.formInline.leaderName, this.formInline.loginNum).then(response => {              
                this.dataApply = response.data.content.list;
                this.listQuery.total = response.data.content.pagination.total;
                this.loading = false;
            });
        },
        // 表单查询
        onSubmit() {
            this.$refs['formInline'].validate((valid) => {
                if (valid) {
                    this.listQuery.page = 1;
                    this.searchFetchData();
                } else {
                    return false;
                }
            });
        },
        subjectDet(row) {
            this.dialog.pid = row.schoolId;
            this.dialog.dialogFormVisible = true;
        },
        // 跳转
        goToAddRole() {
            this.$router.push('addSchool');
        },
        goDetail(row) {
            this.$router.push({path: `leaderInfo/${row}`});
        },
        goToReviseRole(row) {
            this.$router.push({path: `modifySchool/${row}`});
        },
        emptySchoolType() {
            this.formInline.typeSchool = '';
        }
 
    }
}
</script>
<style lang="scss" scoped>
 
.content {
    position: relative;
    padding: 0px;
    $bgcolor:#fff;
    label{
        text-align:left;
    }
    .el-tag{
            margin-left:5px;
            background:#f9f9f9;
            color:#444;
        }
    .formInline {
        .formBtn{
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition{
                position: absolute;
                right:0px; 
                top: 18px;
            }
        }
    }
    .footer{
            text-align:center;
            margin-top:40px;
        }
    .footer .el-button{
            padding:10px 40px;
        }
}
</style>